﻿using System;
using System.Collections.Generic;

namespace YanZhiwei.DotNet3._5.Utilities.Base
{
    /// <summary>
    /// CommonEqualityComparer
    /// <para>rel:http://www.cnblogs.com/ldp615/archive/2011/08/01/distinct-entension.html </para>
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <typeparam name="V">泛型</typeparam>
    public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
    {
        private Func<T, V> keySelector;
        private IEqualityComparer<V> comparer;
        /// <summary>
        ///构造函数
        /// </summary>
        /// <param name="keySelector">委托</param>
        /// <param name="comparer">IEqualityComparer</param>
        public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer)
        {
            this.keySelector = keySelector;
            this.comparer = comparer;
        }
        /// <summary>
        /// 委托
        /// </summary>
        /// <param name="keySelector">委托</param>
        public CommonEqualityComparer(Func<T, V> keySelector)
            : this(keySelector, EqualityComparer<V>.Default)
        { }
        /// <summary>
        /// Equals
        /// </summary>
        /// <param name="x">对象一</param>
        /// <param name="y">对象二</param>
        /// <returns>是否相等</returns>
        public bool Equals(T x, T y)
        {
            return comparer.Equals(keySelector(x), keySelector(y));
        }
        /// <summary>
        /// GetHashCode
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>HashCode</returns>
        public int GetHashCode(T obj)
        {
            return comparer.GetHashCode(keySelector(obj));
        }
    }
}
